package ngat.oss.simulation;

import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.io.*;

import ngat.oss.*;
import ngat.phase2.*;

import jyd.storable.*;
import jyd.collection.*;

public class BasicDBProvider extends UnicastRemoteObject implements DBProvider {

    protected List cache;

    protected long start;

    public BasicDBProvider() throws RemoteException {

	cache = new Vector();
    }

    public void loadCache(String rootName, File dbDir) throws RemoteException {

	try {
	    
	    OSS_Utilities.setDatabaseDir(dbDir);
	    OSS_Utilities.setRootName(rootName);
	    
	    Root root = OSS_Utilities.fetchRoot();
	    
	    cache.clear();
	    
	    System.err.println("Loading phase2 cache...");
	    // Prime the cache.
	    
	    long st = System.currentTimeMillis();
	    int np = 0;
	    
	    Iterator iTag = root.listAllTags();
	    while (iTag.hasNext()) {
		
		Tag tag = (Tag)iTag.next();
		
		Iterator iUser = tag.listAllUsers();
		while (iUser.hasNext()) {
		    
		    User user = (User)iUser.next();
		    
		    Iterator iProp = user.listAllProposals();
		    while (iProp.hasNext()) {
			
			KVPair pair = (KVPair)iProp.next();
			String name = (String)pair.getKey();
			Path   path = new Path(user.getFullPath(), name);
			
			try {
			    
			    Proposal proposal = OSS_Utilities.fetchProposal(path);
			    
			    if (proposal == null) continue;
			    
			    cache.add(proposal);
			    np++;
			    
			} catch (Exception e) {
			    // error loading a proposal....
			    e.printStackTrace();
			}
		    }
		}
	    }
	    long tt = System.currentTimeMillis() - st;
	    System.err.println("Loaded "+np+" proposals in "+(tt/1000)+"S");
	    start = System.currentTimeMillis();
	} catch (Exception e) {
	    throw new RemoteException("Error loading cache", e);
	}
	
    }
    
    public List getCache() throws RemoteException {
	long time = System.currentTimeMillis();
	System.err.println("Cache requested after: "+(time-start)/1000+"S since cache loading");
	start = time;
	return cache;
    }
    
}
